using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Web.UI.WebControls;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;

namespace Starznet.SharePoint.SPDAT.ApplicationPages.Administration
{
    public class LogFileViewPage : Microsoft.SharePoint.ApplicationPages.ApplicationsManagementPage
    {
        protected SPGridView GvLogFile;
        protected ObjectDataSource oData;
        protected EncodedLiteral EncLitDesc;
        protected InputFormTextBox TxtKeywords;
        protected DateTimeControl DtStart;
        protected DateTimeControl DtEnd;

        private string _sPrevFilter = string.Empty;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            string sFileName = Request.QueryString["Name"].ToString();
            string sDesc = this.GetGlobalResourceObject("szadm", "LogView_PageDesc").ToString();
            this.EncLitDesc.Text = String.Format(sDesc, sFileName);

            oData = new ObjectDataSource(typeof(LogFileData).AssemblyQualifiedName, "GetDataTable");
            oData.SelectParameters.Add("FilePath", SPUtility.GetGenericSetupPath("LOGS") + "\\" + sFileName);
            oData.ID = "DataFile";

            if (Request.Form["__CALLBACKID"] == null || Request.Form["__CALLBACKPARAM"] == null || !Request.Form["__CALLBACKID"].EndsWith("GvLogFile"))
            {
                if (ViewState["FilterExpression"] != null)
                {
                    _sPrevFilter = (string)ViewState["FilterExpression"];
                    oData.FilterExpression = _sPrevFilter;
                }
            }
            Controls.Add(oData);

            this.GvLogFile.FilterDataFields = ",Process,TID,Area,Category,,Level,";
            this.GvLogFile.FilteredDataSourcePropertyName = "FilterExpression";
            this.GvLogFile.FilteredDataSourcePropertyFormat = "{1} LIKE '{0}'";

            this.GvLogFile.DataSourceID = "DataFile";
            this.GvLogFile.PageSize = 50;
            this.GvLogFile.AllowPaging = true;
            this.GvLogFile.PagerTemplate = null;
        }

        protected override void OnPreRender(EventArgs e)
        {
            _sPrevFilter = oData.FilterExpression;
            string sFilter = _sPrevFilter;

            if (!string.IsNullOrEmpty(this.TxtKeywords.Text))
            {
                if (!string.IsNullOrEmpty(sFilter)) sFilter += " AND ";
                sFilter += "Message LIKE '%" + this.TxtKeywords.Text + "%'";
            }
            if (!this.DtStart.IsDateEmpty)
            {
                if (!string.IsNullOrEmpty(sFilter)) sFilter += " AND ";
                sFilter += "TimeStamp >= #" + this.DtStart.SelectedDate.ToString("G") + "#";
            }
            if (!this.DtEnd.IsDateEmpty)
            {
                if (!string.IsNullOrEmpty(sFilter)) sFilter += " AND ";
                sFilter += "TimeStamp <= #" + this.DtEnd.SelectedDate.ToString("G") + "#";
            }

            oData.FilterExpression = sFilter;
            ViewState["FilterExpression"] = oData.FilterExpression;

            base.OnPreRender(e);
        }
    
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            GvLogFile.DataBind();
            base.Render(writer);
        }

        protected void BtnSearch_Click(object sender, EventArgs e)
        {
            //Purposely left empty - we just need the postback
        }

        protected void BtnClear_Click(object sender, EventArgs e)
        {
            Response.Redirect("LogFileView.aspx?Name=" + Request.QueryString.Get("Name"));
        }
    }

    public static class LogFileData
    {
        public static DataTable GetDataTable(string FilePath)
        {
            DataTable oDT = new DataTable();
            oDT.Columns.Add("TimeStamp", typeof(DateTime));
            oDT.Columns.Add("Process");
            oDT.Columns.Add("TID");
            oDT.Columns.Add("Area");
            oDT.Columns.Add("Category");
            oDT.Columns.Add("EventID");
            oDT.Columns.Add("Level");
            oDT.Columns.Add("Message");
            oDT.Columns.Add("Correlation");

            string sTextLine;
            DataRow oRow;
            using (StreamReader oS = File.OpenText(FilePath))
            {
                int iRows = 0;
                while (oS.Peek() != -1)
                {
                    iRows++;

                    sTextLine = oS.ReadLine();
                    string[] sSplitText = sTextLine.Split('\t');

                    if (iRows > 1 && !string.IsNullOrEmpty(sTextLine.Trim()))
                    {
                        oRow = oDT.NewRow();
                        int iParts = sSplitText.GetUpperBound(0);

                        if (iParts == 8)
                        {
                            for (int i = 0; i <= iParts; i++)
                            {
                                try
                                {
                                    oRow[i] = sSplitText[i].Trim();
                                }
                                catch
                                {
                                    oRow[i] = DBNull.Value;
                                }
                            }
                            if (iRows != 1)
                                oDT.Rows.Add(oRow);
                        }
                    }
                }
            }
            oDT.AcceptChanges();
            return oDT;
        }
    }
}
